<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">

  <!-- PACE Progress Bar START -->
  
  

  <!-- PACE Progress Bar START -->

  
  <title>
    
    【mightypy】(l/r)strip函数的巨坑 |
    
    ex2tron&#39;s Tech Blog
  </title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="ex2tron,opencv,tensorflow" />
  
  
  
  
  <meta name="description" content="先来猜下Python中这句话的输出是啥">
<meta name="keywords" content="Python,strip,lstrip,rstrip">
<meta property="og:type" content="article">
<meta property="og:title" content="【MightyPy】(l&#x2F;r)strip函数的巨坑">
<meta property="og:url" content="http://ex2tron.wang/mighty-py-strip/index.html">
<meta property="og:site_name" content="ex2tron&#39;s Tech Blog">
<meta property="og:description" content="先来猜下Python中这句话的输出是啥">
<meta property="og:locale" content="en">
<meta property="og:image" content="http://pic.ex2tron.top/mighty_py_strip.jpg">
<meta property="og:updated_time" content="2019-06-30T16:35:06.910Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【MightyPy】(l&#x2F;r)strip函数的巨坑">
<meta name="twitter:description" content="先来猜下Python中这句话的输出是啥">
<meta name="twitter:image" content="http://pic.ex2tron.top/mighty_py_strip.jpg">
  
  <link rel="alternate" href="/atom.xaml" title="ex2tron&#39;s Tech Blog" type="application/atom+xml">
  
  <link rel="icon" href="/img/bookshelf.ico">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");
      font-weight: 500;
      font-style: normal;
    }

    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");
      font-weight: 500;
      font-style: normal;
    }

    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");
      font-weight: lighter;
      font-style: normal;
    }

    @font-face {
      font-family: futura-pt;
      src: url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");
      font-weight: 400;
      font-style: italic;
    }
  </style>

  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1"
    type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css">
  <link rel="stylesheet" href="/css/hiero.css">
  <link rel="stylesheet" href="/css/glyphs.css">
  
  <link rel="stylesheet" href="/css/vdonate.css">
  

  <!-- Custom CSS -->
  <link rel="stylesheet" href="/css/my.css">

  <script>
    (function () {
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
      }
      else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
      }
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>

</head>
<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="ex2tron&#39;s Tech Blog" rel="home"> ex2tron&#39;s Tech Blog </a>
            
          </h1>

          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-【MightyPy】-l-r-strip函数的巨坑" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
<div class="article-gallery">
  <div class="article-gallery-photos">
    
      <a class="article-gallery-img fancybox" href="http://pic.ex2tron.top/mighty_py_strip.jpg" rel="gallery_cjxj6dydi00325w59lmpcxvgv">
        <img src="http://pic.ex2tron.top/mighty_py_strip.jpg" itemprop="image">
      </a>
    
  </div>
</div>

    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      【MightyPy】(l/r)strip函数的巨坑
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/mighty-py-strip/" class="article-date">
	  <time datetime="2019-06-30T14:26:41.000Z" itemprop="datePublished">June 30, 2019</time>
	</a>

      
	<!-- TODO: ex2tron.wang 启用但暂时不显示访问量 2019年3月20日 -->
	<!-- <span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span> -->

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <p>先来猜下Python中这句话的输出是啥<a id="more"></a>：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>filename = <span class="string">"journey_p4.mp4"</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>filename.rstrip(<span class="string">".mp4"</span>)</div></pre></td></tr></table></figure>
<p>答案是：<code>journey_</code>，那<code>p4</code>去哪了呢？怎么样，有兴趣看下去了吗？↓</p>
<blockquote>
<p><em>I Am Iron Man.</em>  ——<a href="https://movie.douban.com/subject/1432146/" target="_blank" rel="external">《钢铁侠》</a><br><em>我就是钢铁侠。</em>——<a href="https://movie.douban.com/subject/1432146/" target="_blank" rel="external">《Iron Man》</a></p>
<p><strong>友情广告：电影台词分享网站：<a href="http://moviequotes.ex2tron.wang/" target="_blank" rel="external">MovieQuotes</a></strong></p>
</blockquote>
<hr>
<h2 id="strip-函数"><a href="#strip-函数" class="headerlink" title="strip()函数"></a>strip()函数</h2><p>Python中常用<code>strip()</code>从字符串的开头和结尾移除指定的字符，不指定参数的话，默认移除的是空格、制表符、换行符等。同样<code>lstrip()</code>和<code>rstrip()</code>分别表示单独从开头、结尾移除指定的字符。</p>
<ul>
<li>函数原型：<a href="https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip" target="_blank" rel="external">str.strip([chars])</a>、<a href="https://docs.python.org/3/library/stdtypes.html?highlight=lstrip#str.lstrip" target="_blank" rel="external">str.lstrip([chars])</a>、<a href="https://docs.python.org/3/library/stdtypes.html?highlight=rstrip#str.rstrip" target="_blank" rel="external">str.rstrip([chars])</a></li>
</ul>
<p>但很多人并不真正了解函数用法，胡乱使用就会导致开头的那种问题，包括之前的我( ╯□╰ )。</p>
<h2 id="填坑"><a href="#填坑" class="headerlink" title="填坑"></a>填坑</h2><p>其实<a href="https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip" target="_blank" rel="external">官方文档</a>上写的很清楚并举了几个例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">The chars argument <span class="keyword">is</span> <span class="keyword">not</span> a prefix <span class="keyword">or</span> suffix; rather, all combinations of its values are stripped.</div></pre></td></tr></table></figure>
<p>翻译过来就是：</p>
<blockquote>
<p>strip函数的参数并不是指前缀或后缀，而是所有其组合值都会被删除掉！</p>
</blockquote>
<p>啥意思呢？以开头问题为例，虽然我们指定了从尾部删除<code>.mp4</code>这个字符串，但它并不会老老实实只删除<code>.mp4</code>，而是包含<code>.mp4</code>所以组合值的字符串都会被删除，比如末尾包含了<code>m/pm/mp/4p/p4/pm4</code>等等都会被删除：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>filename = <span class="string">"journey_p4mmp.mp4"</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>filename.rstrip(<span class="string">".mp4"</span>)	</div><div class="line">journey_</div></pre></td></tr></table></figure>
<p>再来看些官方的例子：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="string">'www.example.com'</span>.strip(<span class="string">'cmowz.'</span>)</div><div class="line">example</div></pre></td></tr></table></figure>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>comment_string = <span class="string">'#....... Section 3.2.1 Issue #32 .......'</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>comment_string.strip(<span class="string">'.#! '</span>)</div><div class="line">Section <span class="number">3.2</span><span class="number">.1</span> Issue <span class="comment">#32</span></div></pre></td></tr></table></figure>
<p><code>strip()</code>函数会从开头和结尾开始检索，直到找到不满足要求的第一个字符为止。所以上面的例子从结尾检索时，遇到2不满足要求就结束了。</p>
<p>综上，<code>strip()/lstrip()/rstrip()</code>要慎用噢。</p>
<h3 id="去扩展名"><a href="#去扩展名" class="headerlink" title="去扩展名"></a>去扩展名</h3><p>p.s.开头那种去扩展名其实有很多实现方式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span>filename = <span class="string">"journey_p4.mp4"</span></div><div class="line"><span class="meta">&gt;&gt;&gt; </span>filename.split(<span class="string">"."</span>)[<span class="number">0</span>]</div><div class="line">journey_p4</div></pre></td></tr></table></figure>
<p>或者用os模块：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">import</span> os</div><div class="line"><span class="meta">&gt;&gt;&gt; </span>os.path.splitext(filename)</div><div class="line">(<span class="string">'journey_p4'</span>, <span class="string">'.mp4'</span>)</div></pre></td></tr></table></figure>
<h2 id="引用"><a href="#引用" class="headerlink" title="引用"></a>引用</h2><ul>
<li><a href="https://docs.python.org/3/library/stdtypes.html?highlight=strip#str.strip" target="_blank" rel="external">str.strip([chars])</a></li>
<li><a href="https://docs.python.org/3/library/stdtypes.html?highlight=lstrip#str.lstrip" target="_blank" rel="external">str.lstrip([chars])</a></li>
<li><a href="https://docs.python.org/3/library/stdtypes.html?highlight=rstrip#str.rstrip" target="_blank" rel="external">str.rstrip([chars])</a></li>
</ul>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/Build篇/">Build篇</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Python/">Python</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/lstrip/">lstrip</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/rstrip/">rstrip</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/strip/">strip</a></li></ul>


      <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div>
      <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{},"image":{"viewList":["qzone","tsina","weixin"],"viewText":"分享到：","viewSize":"16"},"selectShare":{"bdContainerClass":null,"bdSelectMiniList":["qzone","tsina","weixin"]}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
  <script>
    var a = new Donate({
      title: '谢谢支持，我会更加✊~', // 可选参数，打赏标题
      // btnText: 'Donate', // 可选参数，打赏按钮文字
      btnText: '赏', // 可选参数，打赏按钮文字
      el: document.getElementById('donation_div'),
      wechatImage: '/img/wechat.jpg',
      alipayImage: '/img/alipay.jpg'
    });
  </script>
      
                  
      
        
	<div id="comment">
		<!-- 来必力City版安装代码 -->
		<div id="lv-container" data-id="city" data-uid="MTAyMC8yOTQ4MS82MDQ5">
		<script type="text/javascript">
		   (function(d, s) {
		       var j, e = d.getElementsByTagName(s)[0];

		       if (typeof LivereTower === 'function') { return; }

		       j = d.createElement(s);
		       j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
		       j.async = true;

		       e.parentNode.insertBefore(j, e);
		   })(document, 'script');
		</script>
		<noscript>为正常使用来必力评论功能请激活JavaScript</noscript>
		</div>
		<!-- City版安装代码已完成 -->
	</div>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
  
    <a href="/mighty-py-command-line-arguments/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">【MightyPy】处理命令行参数和选项的几种方式</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#strip-函数"><span class="nav-number">1.</span> <span class="nav-text">strip()函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#填坑"><span class="nav-number">2.</span> <span class="nav-text">填坑</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#去扩展名"><span class="nav-number">2.1.</span> <span class="nav-text">去扩展名</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#引用"><span class="nav-number">3.</span> <span class="nav-text">引用</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

        <div class="clearfix container">
          <div class="site-info">
            &copy;
            <!-- 2019
              ex2tron&#39;s Tech Blog All Rights Reserved. -->
              Made by ex2tron | 2019
                <!-- TODO: ex2tron.wang 启用但暂时不显示访问量 2019年3月20日 -->
                <!--  -->
                  <!-- <span id="busuanzi_container_site_uv">
                    本站访客数
                    <span id="busuanzi_value_site_uv"></span>人次 本站总访问量
                    <span id="busuanzi_value_site_pv"></span>次
                  </span> -->
                  <!--  -->
          </div>
          <!-- <div class="site-credit">
            Theme by
              <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
          </div> -->
          <div>
            <p>&nbsp | 电影台词分享：
              <a href="http://moviequotes.ex2tron.wang/" style="font-weight: bold">MovieQuotes</a>
            </p>
          </div>
        </div>
</footer>


<!-- min height -->

<script>
  var contentdiv = document.getElementById("content");

  contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>

<!-- Custome JS -->
<script src="/js/my.js"></script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>







  <div style="display: none;">
    <script src="https://s95.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>
  </div>



	<!-- <script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"> -->
	<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
